﻿#region License
// MIT License
//
// Copyright(c) 2019-2025 ZhangYu
// https://gitee.com/zhangyu800/litebyte
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
#region Intro
// Purpose: API Tool
// Author: ZhangYu
// CreateDate: 2019-10-10
// LastModifiedDate: 2025-08-30
#endregion
namespace LiteByte {

    using LiteByte.Common;
    using LiteByte.Analyzers;
    using System;
    using LiteByte.Converters;

    /// <summary>
    /// <para>LiteByte工具类</para>
    /// </summary>
    public static class LBUtil {

        /// <summary> 写入数据时 缓冲区的最大容量(默认10M) </summary>
        public static int MaxCapacity {
            get { return NumberWriter.MaxCapacity; }
            set { NumberWriter.MaxCapacity = value; }
        }

        /// <summary> 加载自定义类型 | Load custom struct files </summary>
        /// <param name="lbClasses"> 自定义类型代码 </param>
        public static void LoadClasses (params string[] lbClasses) {
            LexicalAnalyzer lexer = new LexicalAnalyzer();
            SyntaxAnalyzer parser = new SyntaxAnalyzer();
            for (int i = 0; i < lbClasses.Length; i++) {
                string lbClass = lbClasses[i];
                SyntaxResult result = parser.Analyze(lexer.Analyze(lbClass));
                if (result.IsSuccess) {
                    ConfigData.AddTypes(result.Types);
                } else {
                    if (lbClass == null) lbClass = "null";
                    throw new Exception($"LoadClasses() error! Analyze class failed! LBClass:\n{lbClass}\n" + result.Error);
                }
            }
            ConfigData.CheckAllTypes();
        }

        /// <summary> 清理已经加载的类型 </summary>
        public static void ClearClasses() {
            ConfigData.ClearTypes();
        }

        /// <summary> 序列化(对象转字节数组) | Serialize(Convert object to bytes) </summary>
        /// <param name="obj">对象(类或结构) | object(class or struct)</param>
        public static byte[] Serialize<T>(T obj) where T : new() {
            return Serialize(obj, typeof(T).Name);
        }

        /// <summary> 序列化(对象转字节数组) | Serialize(Convert object to bytes) </summary>
        /// <param name="obj">对象(类或结构) | object(class or struct)</param>
        /// <param name="className">自定义类型名称 | Custom type name</param>
        public static byte[] Serialize<T>(T obj, string className) where T : new() {
            TypeData lbType = ConfigData.GetType(className);
            if (lbType == null) throw new Exception($"Serialize() error! Class name:{className} not exists! Unloaded class or upper caps error.");
            var writer = new LBWriter();
            writer.WriteObject(obj, lbType);
            return writer.ToBytes();
        }

        /// <summary> 反序列化 | Deserialize(Parse bytes to object) </summary>
        /// <param name="bytes">字节数组 | Byte array</param>
        public static T Deserialize<T>(byte[] bytes) where T : new() {
            return Deserialize<T>(bytes, typeof(T).Name);
        }

        /// <summary> 反序列化 | Deserialize(Parse bytes to object) </summary>
        /// <param name="className">自定义类型名称 | Custom type name</param>
        /// <param name="bytes">字节数组 | Byte array</param>
        public static T Deserialize<T>(byte[] bytes, string className) where T : new() {
            TypeData lbType = ConfigData.GetType(className);
            if (lbType == null) throw new Exception($"Deserialize() error! Class name:{className} not exists! Unloaded class or upper caps error.");
            var reader = new LBReader(bytes);
            return (T)reader.ReadObject(typeof(T), lbType);
        }

    }

}